<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/8/1
 * Time: 9:36
 */

namespace app\command\company;

use app\admin\model\Company;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use app\company\model\Stat as StatModel;

class Stat extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('company:stat')->setDescription('日统计')
             ->addArgument('date', Option::VALUE_REQUIRED, '日期', '')
             ->addArgument('type', Option::VALUE_REQUIRED, '类型', 1);//1.正常执行 2.执行昨天的(校准数据)
    }


    protected function execute(Input $input, Output $output)
    {
        $date = $input->getArgument('date');
        $type = $input->getArgument('type');
        if (!$date) $date = date('Ymd');//如果没有传入日期，则取当前日期
        if ($type == 2) $date = date('Ymd', strtotime('-1 day'));//如果是校准数据，则取前一天的日期
        $date = date('Y-m-d', strtotime($date));
        $output->writeln("开始执行日统计:{$date}");
        $model = new Company();
        $model->startTrans();
        try {
            Company::select()->each(function ($item) use ($date) {
                $map        = [['order_status', 'in', [2, 3, 4]]];
                $company_id = $item->id;
                $type       = 1;
                $year       = date('Y', strtotime($date));//年
                $month      = date('m', strtotime($date));//月
                $quarter    = ceil((date('m', strtotime($date))) / 3);//季度
                //销售金额
                $sales_amount = $item->storeOrderDetailSM($map)->whereDay('dt_store_order.create_time', $date)->sum('amount');
                //销售数量
                $sales_quantity = $item->storeOrderDetailSM($map)->whereDay('dt_store_order.create_time', $date)->sum('quantity');
                //订单数量
                $order_quantity = $item->storeOrders()->where($map)->whereDay('dt_store_order.create_time', $date)->count();
                //退货数量
                $return_quantity = 0;
                //退货金额
                $return_amount = 0;
                //回款金额 todo 订单账期到期时间
                $collection_amount = $item->storeUserCreditSM([])->whereDay('dt_store_user_credit.credit_time', $date)->sum('credit_amount');
                //实收金额 支付方式不等于账期支付的金额
                $received_amount = $item->storeOrderDetailSM($map)->whereDay('dt_store_order.create_time', $date)->where('dt_store_order.pay_type', '<>', 3)->sum('amount');
                //账期金额
                $bill_amount = $item->storeOrderDetailSM($map)->whereDay('dt_store_order.create_time', $date)->where('dt_store_order.pay_type', 3)->sum('amount');
                //采购金额 统计已完成状态的
                $map             = [['order_status', '=', 5]];
                $purchase_amount = $item->companyOrderDetailSM($map)->whereDay('dt_company_order.create_time', $date)->sum('amount');
                //采购数量
                $purchase_quantity = $item->companyOrderDetailSM($map)->whereDay('dt_company_order.create_time', $date)->sum('quantity');
                //采购订单数量
                $purchase_order_quantity = $item->companyOrders()->whereDay('create_time', $date)->count();
                $arr                     = compact('sales_amount', 'sales_quantity', 'order_quantity', 'return_quantity', 'return_amount', 'collection_amount',
                    'received_amount', 'bill_amount', 'purchase_amount', 'purchase_quantity', 'purchase_order_quantity', 'company_id', 'type',
                    'year', 'month', 'quarter');
                if (!$model = StatModel::gs($item->id)->whereDay('create_time', $date)->type(1)->find()) {
                    $model = new StatModel();
                }
                $model->save($arr);

                $field = "sum(sales_amount) sales_amount, sum(sales_quantity) sales_quantity,sum(order_quantity) order_quantity, sum(return_quantity) return_quantity,
              sum(return_amount) return_amount, sum(collection_amount) collection_amount, sum(received_amount) received_amount, sum(bill_amount) bill_amount, 
              sum(purchase_amount) purchase_amount, sum(purchase_quantity) purchase_quantity,  sum(purchase_order_quantity) purchase_order_quantity,min(company_id) company_id";

                //更新本年的
                if (!$yearModel = StatModel::gs($item->id)->type(5)->where('year', $year)->find()) {
                    $yearModel = new StatModel();
                }
                $arr         = StatModel::gs($item->id)->type(1)->where('year', $year)->field($field)->find()->toArray();
                $arr['year'] = $year;
                $arr['type'] = 5;
                $yearModel->save($arr);
                //更新季度的
                if (!$quarterModel = StatModel::gs($item->id)->type(4)->where('year', $year)->where('quarter', $quarter)->find()) {
                    $quarterModel = new StatModel();
                }
                $arr            = StatModel::gs($item->id)->type(1)->where('year', $year)->where('quarter', $quarter)->field($field)->find()->toArray();
                $arr['year']    = $year;
                $arr['quarter'] = $quarter;
                $arr['type']    = 4;
                $quarterModel->save($arr);
                //更新本月的
                if (!$monthModel = StatModel::gs($item->id)->type(3)->where('year', $year)->where('month', $month)->find()) {
                    $monthModel = new StatModel();
                }
                $arr          = StatModel::gs($item->id)->type(1)->where('year', $year)->where('month', $month)->field($field)->find()->toArray();
                $arr['year']  = $year;
                $arr['month'] = $month;
                $arr['type']  = 3;
                $monthModel->save($arr);
            });
            $model->commit();
            $output->writeln("执行成功");
        } catch (Exception $e) {
            $model->rollback();
            $output->writeln("执行失败----" . $e->getMessage());
        }
    }
}